package com.train.common.utils.io;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.util.IOUtils;
import com.train.common.enums.impl.SysExceptionEnums;
import com.train.common.exception.GlobalException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.rmi.ServerException;

public class IoUtils {

    /**
     * 将指定目录下的文件进行输出
     * @param path
     * @param outputStream
     */
    public static void write(String path, boolean isClose, OutputStream outputStream) {
        File file = new File(path);
        if (!file.exists()) {
            throw new GlobalException(SysExceptionEnums.EXP_FILE_NOT_EXISTS);
        }
        BufferedOutputStream os = new BufferedOutputStream(outputStream);
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(Files.newInputStream(file.toPath()));
            IoUtil.write(os, isClose, in.readAllBytes());
        } catch (IOException e) {
            throw new GlobalException(e.getMessage());
        } finally {
            IOUtils.close(os);
            IOUtils.close(in);
        }
    }

    /**
     * 输出影像流
     * @param response
     * @param image
     */
    public static void writeImage(HttpServletResponse response, BufferedImage image) {
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            throw new GlobalException(e.getMessage());
        }
    }

    /**
     * 从指定路径读取内容
     * @param filePath
     * @return
     * @throws IORuntimeException
     */
    public static byte[] read(String filePath) throws IORuntimeException, IOException {
        BufferedInputStream inputStream = new BufferedInputStream(Files.newInputStream(Paths.get(filePath)));
        return inputStream.readAllBytes();
    }

    /**
     * 从输入流读取内容
     * @param in
     * @param isClose
     * @return
     * @throws IORuntimeException
     */
    public static String readUtf8(InputStream in, boolean isClose) throws IORuntimeException {
        return StrUtil.utf8Str(IoUtil.read(in, isClose));
    }

    /**
     * BufferedImage转字节
     * @param image
     * @return
     */
    public static byte[] toByte(BufferedImage image) {
        byte[] imageBytes;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "jpg", baos);
            baos.flush();
            imageBytes = baos.toByteArray();
        } catch (IOException e) {
            throw new GlobalException(e.getMessage());
        }
        return imageBytes;
    }
}
